package com.yl.project.lvyou.frontapp.controller;

import com.yl.common.utils.DateUtils;
import com.yl.common.utils.StringUtils;
import com.yl.framework.web.controller.BaseController;
import com.yl.framework.web.domain.AjaxResult;
import com.yl.project.lvyou.booking.domain.TicketBooking;
import com.yl.project.lvyou.booking.service.ITicketBookingService;
import com.yl.project.lvyou.feedback.domain.UserFeedback;
import com.yl.project.lvyou.feedback.service.IUserFeedbackService;
import com.yl.project.lvyou.info.domain.SpotInfo;
import com.yl.project.lvyou.info.service.ISpotInfoService;
import com.yl.project.lvyou.knowledge.domain.QaKnowledge;
import com.yl.project.lvyou.knowledge.service.IQaKnowledgeService;
import com.yl.project.lvyou.questions.domain.UnmatchedQuestions;
import com.yl.project.lvyou.questions.service.IUnmatchedQuestionsService;
import com.yl.project.lvyou.record.domain.PaymentRecord;
import com.yl.project.lvyou.record.service.IPaymentRecordService;
import com.yl.project.lvyou.records.domain.UserConsultRecords;
import com.yl.project.lvyou.records.service.IUserConsultRecordsService;
import com.yl.project.lvyou.spot.domain.ScenicSpot;
import com.yl.project.lvyou.spot.service.IScenicSpotService;
import com.yl.project.lvyou.video.domain.ScenicVideo;
import com.yl.project.lvyou.video.service.IScenicVideoService;
import com.yl.project.system.dict.domain.DictData;
import com.yl.project.system.dict.service.IDictDataService;
import com.yl.project.system.files.domain.UploadedFiles;
import com.yl.project.system.files.service.IUploadedFilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/lvyou/app")
public class ScenicAppController extends BaseController{

        @Autowired
        private IScenicSpotService scenicSpotService;

        @Autowired
        private IUploadedFilesService uploadedFilesService;

        @Autowired
        private IScenicVideoService scenicVideoService;

        @Autowired
        private IDictDataService dictDataService;

        @Autowired
        private ITicketBookingService ticketBookingService;

        @Autowired
        private IPaymentRecordService paymentRecordService;

        @Autowired
        private IQaKnowledgeService qaKnowledgeService;

        @Autowired
        private IUnmatchedQuestionsService unmatchedQuestionsService;

        @Autowired
        private IUserConsultRecordsService userConsultRecordsService;

        @Autowired
        private IUserFeedbackService userFeedbackService;

        @Autowired
        private ISpotInfoService spotInfoService;

    /**
     * 首页轮播图
      * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/banner")
    @ResponseBody
    public AjaxResult banner()
    {
        ScenicSpot scenicSpot = new ScenicSpot();
        scenicSpot.setIsBanner(1);
        List<ScenicSpot> list = scenicSpotService.selectScenicSpotNews(scenicSpot);
        return AjaxResult.success(list);
    }

    /**
     * 旅游景区
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/news")
    @ResponseBody
    public AjaxResult news(ScenicSpot scenicSpot)
    {
        startPage();
        List<ScenicSpot> list = scenicSpotService.selectScenicSpotNews(scenicSpot);
        return AjaxResult.success(getDataTable(list));
    }

    /**
     * 旅游景区资讯
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/info")
    @ResponseBody
    public AjaxResult info(SpotInfo spotInfo)
    {
        startPage();
        List<SpotInfo> list = spotInfoService.selectSpotInfoList(spotInfo);
        return AjaxResult.success(getDataTable(list));
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/spotInfo")
    @ResponseBody
    public AjaxResult spotInfo(Long id,Boolean isLvyouinfo)
    {
        ScenicSpot scenicSpot = scenicSpotService.selectScenicSpotNewsById(id);
        if(isLvyouinfo){
            scenicSpot.setVisitCount(scenicSpot.getVisitCount()+1);
            scenicSpotService.updateScenicSpot(scenicSpot);
        }
        return AjaxResult.success(scenicSpot);
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/infoNew")
    @ResponseBody
    public AjaxResult infoNew(Long id)
    {
        SpotInfo spotInfo = spotInfoService.selectSpotInfoById(id);
        return AjaxResult.success(spotInfo);
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/info/visit")
    @ResponseBody
    public AjaxResult infoVisit(SpotInfo spotInfo)
    {
        spotInfoService.updateSpotInfo(spotInfo);
        return AjaxResult.success();
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/info/like")
    @ResponseBody
    public AjaxResult infoLike(SpotInfo spotInfo)
    {
        spotInfoService.updateSpotInfo(spotInfo);
        return AjaxResult.success();
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/spotPic")
    @ResponseBody
    public AjaxResult spotPic(Long id)
    {
        UploadedFiles uploadedFiles= new UploadedFiles();
        uploadedFiles.setYewuId(id);
        uploadedFiles.setYewuName("SPOT");
        List<UploadedFiles> list = uploadedFilesService.selectUploadedFilesList(uploadedFiles);
        return AjaxResult.success(list);
    }

    /**
     * 查询导览视频
     * @param id
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/spotAudio")
    @ResponseBody
    public AjaxResult spotAudio(Long id)
    {
        ScenicVideo scenicVideo = new ScenicVideo();
        scenicVideo.setScenicId(id);
         scenicVideo = scenicVideoService.selectOne(scenicVideo);
        return AjaxResult.success(scenicVideo);
    }

    /**
     * 查询旅游偏好字典
     * @param id
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getDictData")
    @ResponseBody
    public AjaxResult getDictData(Long id)
    {
        DictData dictData=new DictData();
        dictData.setDictType("sys_travel_preferences");
        List<DictData> dictDataList =dictDataService.selectDictDataList(dictData);
        return AjaxResult.success(dictDataList);
    }
    /**
     * 查询旅游偏好字典
     * @param id
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getDictData/spotType")
    @ResponseBody
    public AjaxResult getDictDataSpotType(Long id)
    {
        DictData dictData=new DictData();
        dictData.setDictType("sys_spot_type");
        List<DictData> dictDataList =dictDataService.selectDictDataList(dictData);
        return AjaxResult.success(dictDataList);
    }

    /**
     * 预订保存
     * @param ticketBooking
     * @return
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/ticket/booking")
    @ResponseBody
    public AjaxResult booking(@RequestBody TicketBooking ticketBooking)
    {
       String dataTime =  DateUtils.dateTimeNow();
       int sjs =(int)((Math.random()*9+1)*100000);
        ticketBooking.setOrderNo("MP"+dataTime+sjs);
        ticketBookingService.insertTicketBooking(ticketBooking);
        return AjaxResult.success(ticketBooking);
    }


    /**
     * 订单详情
     * @param ticketBooking
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/order/detail")
    @ResponseBody
    public AjaxResult orderDetail( TicketBooking ticketBooking){
        return AjaxResult.success(ticketBookingService.selectByOrderNo(ticketBooking));
    }


    /**
     * 订单支付
     * @param
     * @return
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/payment/pay")
    @ResponseBody
    public AjaxResult paymentPay(@RequestBody PaymentRecord paymentRecord){
        paymentRecord.setPaymentStatus(0);
        if(StringUtils.isNotEmpty(paymentRecord.getOrderNo())){
            PaymentRecord  record = paymentRecordService.selectPaymentRecordByOrderNo(paymentRecord.getOrderNo());
            if(record==null){
                TicketBooking ticketBook = new TicketBooking();
                ticketBook.setOrderNo(paymentRecord.getOrderNo());
                TicketBooking ticketBooking =ticketBookingService.selectByOrderNo(ticketBook);
                ScenicSpot scenicSpot = new ScenicSpot();
                scenicSpot.setId(ticketBooking.getScenicId());
                ScenicSpot ticketNum =scenicSpotService.selectScenicSpotById(ticketBooking.getScenicId());
                if(ticketNum.getTicketNum()>=ticketBooking.getTicketCount()){
                    ticketBooking.setStatus(1);
                    ticketBooking.setPaymentTime(DateUtils.getNowDate());
                    ticketBookingService.updateTicketBookingStatus(ticketBooking);
                    //库存进行修改
                    ticketNum.setTicketNum(ticketNum.getTicketNum()-ticketBooking.getTicketCount());
                    scenicSpotService.updateScenicSpot(ticketNum);
                    paymentRecord.setPaymentTime(DateUtils.getNowDate());
                    paymentRecord.setPaymentStatus(1);
                    return AjaxResult.success(paymentRecordService.insertPaymentRecord(paymentRecord));
                }else{
                    return AjaxResult.error("库存不足");
                }

            }else{
                return AjaxResult.error("订单已支付");
            }

        }else{
            return AjaxResult.error();
        }
    }

    /**
     * 取消订单
     * @param paymentRecord
     * @return
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/order/cancel")
    @ResponseBody
    public AjaxResult orderCancel(@RequestBody PaymentRecord paymentRecord){
        paymentRecord.setPaymentStatus(0);
        if(StringUtils.isNotEmpty(paymentRecord.getOrderNo())){
            PaymentRecord  record = paymentRecordService.selectPaymentRecordByOrderNo(paymentRecord.getOrderNo());
            if(record==null){
                TicketBooking ticketBooking = new TicketBooking();
                ticketBooking.setOrderNo(paymentRecord.getOrderNo());
                ticketBooking.setStatus(2);
                ticketBookingService.updateTicketBookingStatus(ticketBooking);
                return AjaxResult.success();
            }else{
                return AjaxResult.error("订单已支付");
            }

        }else{
            return AjaxResult.error();
        }
    }

    /**
     * 订单列表
     * @param
     * @return
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/order/list")
    @ResponseBody
    public AjaxResult orderList(TicketBooking ticketBooking)
    {
        startPage();
        List<TicketBooking> list = ticketBookingService.selectTicketBookingList(ticketBooking);
        return AjaxResult.success(getDataTable(list));
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/qa/preset")
    @ResponseBody
    public AjaxResult qapPeset(QaKnowledge qaKnowledge)
    {
        qaKnowledge.setIsPreset(1);
        return AjaxResult.success(qaKnowledgeService.selectQaKnowledgeListQa(qaKnowledge));
    }
     @CrossOrigin(origins = "*")
        @PostMapping("/qa/answer")
        @ResponseBody
        public AjaxResult qapAnswer(@RequestBody  QaKnowledge qaKnowledge)
        {

            QaKnowledge knowledge =qaKnowledgeService.selectQaKnowledgeAnswert(qaKnowledge);
             if(knowledge!=null ){ //成功匹配到问题
                 UserConsultRecords userConsultRecords = new UserConsultRecords();
                 userConsultRecords.setUserId(qaKnowledge.getUserId());
                 userConsultRecords.setScenicId(qaKnowledge.getScenicId());
                 userConsultRecords.setQuestion(qaKnowledge.getQuestion());
                 userConsultRecords.setAnswer(knowledge.getAnswer());
                 userConsultRecords.setQaId(knowledge.getId());
                 userConsultRecords.setIsMatched(1);
                 userConsultRecordsService.insertUserConsultRecords(userConsultRecords);
             }else{ //没有匹配到问题
                 UserConsultRecords userConsultRecords = new UserConsultRecords();
                 userConsultRecords.setUserId(qaKnowledge.getUserId());
                 userConsultRecords.setScenicId(qaKnowledge.getScenicId());
                 userConsultRecords.setQuestion(qaKnowledge.getQuestion());
                 userConsultRecords.setAnswer("非常不好意思！这个问题我回答不了，相关问题请向人工反馈。");
                 userConsultRecords.setIsMatched(0);
                 userConsultRecordsService.insertUserConsultRecords(userConsultRecords);
                 //添加未匹配问题统计表
                 UnmatchedQuestions unmatchedQuestions= new UnmatchedQuestions();
                 unmatchedQuestions.setQuestion(qaKnowledge.getQuestion());
                 UnmatchedQuestions questions=unmatchedQuestionsService.selectUnmatchedQuestionsByQuestions(unmatchedQuestions);
                 if(questions==null){ //统计表中无数据
                     unmatchedQuestions.setScenicId(qaKnowledge.getScenicId());
                     unmatchedQuestions.setCount(1);
                     unmatchedQuestionsService.insertUnmatchedQuestions(unmatchedQuestions);
                 }else{
                     unmatchedQuestions.setId(questions.getId());
                     unmatchedQuestions.setCount(questions.getCount()+1);
                     unmatchedQuestionsService.updateUnmatchedQuestions(unmatchedQuestions);
                 }
             }
            return AjaxResult.success(knowledge);
        }

    /**
     * 用户反馈
     * @param
     * @return
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/feedback/submit")
    @ResponseBody
    public AjaxResult feedbackSubmit(@RequestBody UserFeedback userFeedback)
    {
        return AjaxResult.success(userFeedbackService.insertUserFeedback(userFeedback));
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/comment/like")
    @ResponseBody
    public AjaxResult commentLike( ScenicSpot scenicSpot)
    {
        scenicSpot.setLikeCount(scenicSpot.getLikeCount()+1);
        return AjaxResult.success(scenicSpotService.updateScenicSpot(scenicSpot));
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/scenic/getLikeCount")
    @ResponseBody
    public AjaxResult getLikeCount( Long id)
    {
        return AjaxResult.success(scenicSpotService.selectScenicSpotById(id));
    }

    @CrossOrigin(origins = "*")
    @PostMapping("/scenic/addLike")
    @ResponseBody
    public AjaxResult addLike(@RequestBody ScenicSpot scenicSpot)
    {
        scenicSpot.setLikeCount(scenicSpot.getLikeCount());
        return AjaxResult.success(scenicSpotService.updateScenicSpot(scenicSpot));
    }
}
